import { Injectable } from '@nestjs/common';
import { ReturnModelType } from '@typegoose/typegoose';
import { Tab } from 'libs/db/src/model/tab.model';
import { TabCollection } from 'libs/db/src/model/tabCollection.model';
import { TabDetail } from 'libs/db/src/model/tabDetail.model';
import { InjectModel } from 'nestjs-typegoose';
import { CreateTabItemDto } from 'src/tab/createTabItem.dto';
import { TabService } from 'src/tab/tab.service';
import { TabCollectionDetailDto } from './dto/TabCollectionDetail.dto';

@Injectable()
export class TabCollectionService {
  constructor(
    @InjectModel(TabCollection)
    private readonly collectionModel: ReturnModelType<typeof TabCollection>,
    @InjectModel(TabDetail)
    private readonly detailModel: ReturnModelType<typeof TabDetail>,
    private readonly tabService: TabService,
  ) {}

  async create(tabs: [CreateTabItemDto], workspaceId: string, name: string) {
    const tabCollection = await this.collectionModel.create({
      workspaceId,
      name,
    });
    for (let tab of tabs) {
      this.tabService.create(tabCollection.id, tab);
    }

    return;
  }

  async createEmptyCustomed(wid: string): Promise<void> {
    await this.collectionModel.create({
      workspaceId: wid,
      isCustomed: true,
    });
    return;
  }

  async findAllCollectionByWid(workspaceId: string): Promise<TabCollection[]> {
    return await this.collectionModel.find({
      workspaceId,
    });
  }

  async findCollectionByIsCustomed(
    workspaceId: string,
    isCustomed: boolean,
  ): Promise<TabCollection[]> {
    return await this.collectionModel.find({ workspaceId, isCustomed });
  }

  async findDetail(collectionId: string): Promise<TabCollectionDetailDto> {
    const collection = await this.findOneById(collectionId);
    //首先查找TabDetail当中与collectionId的关系
    const details = await this.detailModel.find({
      collectionId,
    });
    const tabs: Tab[] = [];
    // 然后将所有的Tab对应的信息获取
    for (const detail of details) {
      const tabId = detail.tabId;
      // console.log(tabId);
      const tab = await this.tabService.findOneById(tabId);
      // console.log(tab);
      tabs.push(tab);
    }

    return {
      id: collection.id.toString(),
      createTime: collection.createdAt.getTime(),
      tabItems: tabs,
    };
  }

  async findOneById(collectionId: string): Promise<TabCollection | undefined> {
    return await this.collectionModel.findById(collectionId);
  }

  async remove(collectionId: string) {
    //先去删除这个collection下的所有关联tab和记录
    const details = await this.detailModel.find({
      collectionId,
    });

    for (const detail of details) {
      // 先删除引用记录
      await this.detailModel.remove(detail);
      // 再删除tab
      await this.tabService.remove(detail.tabId);
    }

    await this.collectionModel.remove({ _id: collectionId });
  }

  async modify(cid, newWid) {
    return await this.collectionModel.findByIdAndUpdate(cid, {
      workspaceId: newWid,
    });
  }
}
